package com.nycreativity.elecreativity.service.impl;

import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.kotlin.KtUpdateWrapper
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.nycreativity.elecreativity.entity.enums.IsDefaultEnum
import com.nycreativity.elecreativity.entity.enums.IsDelEnum
import com.nycreativity.elecreativity.entity.param.address.AddressAddParam
import com.nycreativity.elecreativity.entity.param.address.AddressUpdateParam
import com.nycreativity.elecreativity.entity.po.Address
import com.nycreativity.elecreativity.mapper.AddressMapper
import com.nycreativity.elecreativity.service.AddressService
import com.nycreativity.elecreativity.util.MappingUtil
import com.nycreativity.elecreativity.util.usersession.UserContext
import org.springframework.stereotype.Service
import java.time.LocalDateTime
import javax.annotation.Resource

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sxt && ttxxi
 * @since 2021-03-10
 */
@Service
class AddressServiceImpl : ServiceImpl<AddressMapper, Address>(), AddressService {

    @Resource
    lateinit var addressMapper: AddressMapper

    override fun queryByUserId(userId: Long): List<Address> {
        val ktQueryWrapper = KtQueryWrapper(Address::class.java)
                .eq(Address::userId , userId)
                .eq(Address::isDel, IsDelEnum.NO.code)
                .orderByDesc(Address::id)
        return addressMapper.selectList(ktQueryWrapper)
    }

    override fun add(addressAddParam: AddressAddParam): Boolean {

        val address = MappingUtil.getMappingObject(addressAddParam, Address::class.java)
        if(address == null || address.isEmpty()){
            return false
        }
        //获取当前用户
        val loginUser = UserContext.get()
        address.apply {
            userId = loginUser?.id
            isDefault = IsDefaultEnum.NO.code
            createTime = LocalDateTime.now()
            creator = loginUser?.id
        }
        addressMapper.insert(address)
        return true

    }

    override fun updateById(addressUpdateParam: AddressUpdateParam): Boolean {
        val address = MappingUtil.getMappingObject(addressUpdateParam, Address::class.java)
        if (address == null || address.isEmpty()){
            return false
        }
        //获取当前用户
        val loginUser = UserContext.get()
        address.apply {
            modifyTime = LocalDateTime.now()
            modifier = loginUser?.id
        }
        addressMapper.updateById(address)
        return true

    }

    override fun deleteById(id: Long) {
        val wrapper = KtUpdateWrapper(Address::class.java)
                .set(Address::isDel, IsDelEnum.YES.code)
                .set(Address::modifier, UserContext.get()?.id)
                .set(Address::modifyTime, LocalDateTime.now())
                .eq(Address::id, id)
        addressMapper.update(null, wrapper)
    }

}
